let rows = 2000
const argv = [...process.argv]
argv.forEach((item, index) => {
  if (item === '--line' || item === '--row') {
    if (typeof argv[index + 1] === 'number') {
      rows = [index + 1]
    }
  }
})
const fs = require('fs')
const readline = require('readline')
const path = require('path')
const fileList = fs.readdirSync(path.join(__dirname, './static/'))

const writeFile = (bookName) => {
  let arr = []
  const _name = bookName.split('.')
  _name.pop()
  const name = _name.join('.')
  const readStream = fs.createReadStream(
    path.join(__dirname, './static/', bookName)
  )
  fs.mkdirSync(path.join(__dirname, 'dist', name), {
    recursive: true,
  })
  const readliner = readline.createInterface({ input: readStream })

  readliner.on('line', (data) => {
    arr.push(data)
  })
  readliner.on('close', () => {
    //结束后调用的
    for (let i = 0; i < Math.ceil(arr.length / rows); i++) {
      let writeName = path.join(__dirname, `dist/${name}/${name}-${i}.txt`)
      fs.writeFile(
        writeName,
        arr.slice(i * rows, i * rows + rows).join('\r\n'),
        () => {}
      )
    }
  })
}

fileList.forEach((filename) => {
  const suffix = path.extname(filename)
  if (suffix === '.txt') {
    writeFile(filename)
  }
})
